import time

from pymongo import MongoClient
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

if __name__ == '__main__':
    driver = webdriver.Chrome()
    # url = 'https://music.163.com/discover/playlist/?order=hot&cat=全部limit=35&offset=35'
    url = 'https://music.163.com/#/discover/playlist/?order=hot&cat=%E5%85%A8%E9%83%A8limit%3D35&limit=35&offset=0'
    print('歌单名称\t\t\t\t\t播放量\t\t链接')
    driver.get(url)
    # driver.implicitly_wait(30)
    # 使用XPATH定位ifram框架位置
    ifram = driver.find_element(By.XPATH,'//*[@id="g_iframe"]')
    driver.switch_to.frame(ifram)
    # 定位热门按钮
    hot = driver.find_element(By.CLASS_NAME,'a1')
    ActionChains(driver).click(hot).perform()
    # 准备存入MangoDB
    client = MongoClient()
    db = client.student
    coll = db.musicList


    for i in range(10):
        driver.set_page_load_timeout(30)
        # 定位所有的热门音乐
        elements = driver.find_elements(By.CLASS_NAME,'u-cover')
        for element in elements:
            # 定位点赞数
            nb = element.find_element(By.CLASS_NAME,'nb').text
            if nb[-1] == '万':
                # 分割点赞数的数字
                if int(nb.split('万')[0]) >= 500:
                    # 定位歌单链接获取歌单名称
                    playlist = element.find_element(By.CLASS_NAME,'msk').get_attribute('title')
                    # 定位歌单链接获取歌单
                    link = element.find_element(By.CLASS_NAME, 'msk').get_attribute('href')
                    print('playlist:',type(playlist))
                    # 写入Mangodb数据库
                    coll.insert_one({'歌单名称':playlist,'播放量':nb,'歌单链接':link})
                    print(f'{playlist}\t\t\t\t\t{nb}\t\t{link}')
                else:
                    continue
        print(f'获取完第{i+1}遍')
        time.sleep(3)
        next = driver.find_element(By.CLASS_NAME, 'znxt')
        driver.execute_script("arguments[0].scrollIntoView()", next)
        ActionChains(driver).click(next).perform()
        print('下一页已点击')


